package com.example.weight.greenSeasons.compost;

import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.weight.R;
import com.example.weight.config.Config;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;

import net.cachapa.expandablelayout.ExpandableLayout;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;

public class DuifeiFajiaowendu extends AppCompatActivity {

    private TitleBar titleBar;
    //日期
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
    SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("HH:mm");
    Date incomingDate = new Date(System.currentTimeMillis());
    private TextView jilu_date,jilu_time;
    Calendar calendar= Calendar.getInstance(Locale.CHINA);
    //表读数
    private EditText cao3_dunkuangbianhao,cao3_diyitian,cao3_diertian,cao3_disantian,cao3_disitian,cao3_diwutian,cao3_diliutian,cao3_diqitian,cao3_dibatian;
    private EditText cao4_dunkuangbianhao,cao4_diyitian,cao4_diertian,cao4_disantian,cao4_disitian,cao4_diwutian,cao4_diliutian,cao4_diqitian,cao4_dibatian;

    //备注
    private EditText neibuwendu,waibuwendu,remark;
    //用户、抄表人
    private String name,factory;
    private ExpandableLayout expand_3,expand_4;
    private Button textView3,textView4;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_duifeigongyi_fajiaowendu);

        //页面返回按钮
        titleBar=findViewById(R.id.titleBar);
        titleBar.setOnTitleBarListener(new OnTitleBarListener() {
            @Override
            public void onLeftClick(View v) {
                DuifeiFajiaowendu.this.finish();
            }
            @Override
            public void onTitleClick(View v) {
            }
            @Override
            public void onRightClick(View v) {
            }
        });


        //日期
        simpleDateFormat1.setTimeZone(TimeZone.getTimeZone("Etc/GMT-8"));
        jilu_time = findViewById(R.id.jilu_time);
        jilu_time.setText(simpleDateFormat1.format(incomingDate));
        jilu_date = findViewById(R.id.jilu_date);
        jilu_date.setText(simpleDateFormat.format(incomingDate));

        //用户
        Intent previousIntent = getIntent();
        name = previousIntent.getStringExtra("name");
        factory = previousIntent.getStringExtra("factory");

        expand_3=findViewById(R.id.expandable_3);
        expand_4=findViewById(R.id.expandable_4);
        textView3=findViewById(R.id.textView_3);
        textView4=findViewById(R.id.textView_4);

        cao3_dunkuangbianhao=findViewById(R.id.cao3_dunkuangbianhao);
        cao3_diyitian=findViewById(R.id.cao3_diyitian);
        cao3_diertian=findViewById(R.id.cao3_diertian);
        cao3_disantian=findViewById(R.id.cao3_disantian);
        cao3_disitian=findViewById(R.id.cao3_disitian);
        cao3_diwutian=findViewById(R.id.cao3_diwutian);
        cao3_diliutian=findViewById(R.id.cao3_diliutian);
        cao3_diqitian=findViewById(R.id.cao3_diqitian);
        cao3_dibatian=findViewById(R.id.cao3_dibatian);
        cao4_dunkuangbianhao=findViewById(R.id.cao4_dunkuangbianhao);
        cao4_diyitian=findViewById(R.id.cao4_diyitian);
        cao4_diertian=findViewById(R.id.cao4_diertian);
        cao4_disantian=findViewById(R.id.cao4_disantian);
        cao4_disitian=findViewById(R.id.cao4_disitian);
        cao4_diwutian=findViewById(R.id.cao4_diwutian);
        cao4_diliutian=findViewById(R.id.cao4_diliutian);
        cao4_diqitian=findViewById(R.id.cao4_diqitian);
        cao4_dibatian=findViewById(R.id.cao4_dibatian);

        neibuwendu=findViewById(R.id.neibuwendu);
        waibuwendu=findViewById(R.id.waibuwendu);
        remark=findViewById(R.id.remark);

        //获取当天最新一条数据
        RequestQueue queue = Volley.newRequestQueue(this);
        String url = Config.url + "/sjq/sjqCompostProcessFermentation/getlast" + "?factory=" + factory;
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            JSONObject data = jsonObject.getJSONObject("data");
                            if (!data.isNull("id") && data.getString("factory").equals(factory)) {
                                cao3_dunkuangbianhao.setHint(data.getString("thirdNum").equals("null")?"":data.getString("thirdNum"));
                                cao3_diyitian.setHint(data.getString("thirdOne").equals("null")?"":data.getString("thirdOne"));
                                cao3_diertian.setHint(data.getString("thirdTwo").equals("null")?"":data.getString("thirdTwo"));
                                cao3_disantian.setHint(data.getString("thirdThree").equals("null")?"":data.getString("thirdThree"));
                                cao3_disitian.setHint(data.getString("thirdFour").equals("null")?"":data.getString("thirdFour"));
                                cao3_diwutian.setHint(data.getString("thirdFive").equals("null")?"":data.getString("thirdFive"));
                                cao3_diliutian.setHint(data.getString("thirdSix").equals("null")?"":data.getString("thirdSix"));
                                cao3_diqitian.setHint(data.getString("thirdSeven").equals("null")?"":data.getString("thirdSeven"));
                                cao3_dibatian.setHint(data.getString("thirdEight").equals("null")?"":data.getString("thirdEight"));
                                cao4_dunkuangbianhao.setHint(data.getString("fourthNum").equals("null")?"":data.getString("fourthNum"));
                                cao4_diyitian.setHint(data.getString("fourthOne").equals("null")?"":data.getString("fourthOne"));
                                cao4_diertian.setHint(data.getString("fourthTwo").equals("null")?"":data.getString("fourthTwo"));
                                cao4_disantian.setHint(data.getString("fourthThree").equals("null")?"":data.getString("fourthThree"));
                                cao4_disitian.setHint(data.getString("fourthFour").equals("null")?"":data.getString("fourthFour"));
                                cao4_diwutian.setHint(data.getString("fourthFive").equals("null")?"":data.getString("fourthFive"));
                                cao4_diliutian.setHint(data.getString("fourthSix").equals("null")?"":data.getString("fourthSix"));
                                cao4_diqitian.setHint(data.getString("fourthSeven").equals("null")?"":data.getString("fourthSeven"));
                                cao4_dibatian.setHint(data.getString("fourthEight").equals("null")?"":data.getString("fourthEight"));
                                neibuwendu.setHint(data.getString("internalTemperature").equals("null")?"":data.getString("internalTemperature"));
                                waibuwendu.setHint(data.getString("externalTemperature").equals("null")?"":data.getString("externalTemperature"));
                                remark.setHint(data.getString("remark").equals("null")?"":data.getString("remark"));
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(DuifeiFajiaowendu.this,
                        "获取信息失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(stringRequest);
    }
    //    选择日期
    @SuppressLint({"DefaultLocale", "ResourceType"})
    public void selectDate(View view){
        int YEAR = calendar.get(Calendar.YEAR);
        int MONTH = calendar.get(Calendar.MONTH);
        int DAY = calendar.get(Calendar.DAY_OF_MONTH);
        new DatePickerDialog(this, 2, (view1, year, month, day) -> {
            // 更新EditText控件日期 小于10加0
            jilu_date.setText(new StringBuilder()
                    .append(year)
                    .append("-")
                    .append((month + 1) < 10 ? "0"+ (month + 1) : (month + 1))
                    .append("-")
                    .append((day < 10) ? "0" + day : day));
        },YEAR, MONTH, DAY).show();
    }
    @SuppressLint({"DefaultLocale", "ResourceType"})
    public void selectTime(View view){
        int HOUR = calendar.get(Calendar.HOUR_OF_DAY);
        int MINUTE = calendar.get(Calendar.MINUTE);
        new TimePickerDialog(this, 2, (view11, hourOfDay, minute) -> {
            // 更新EditText控件日期 小于10加0
            jilu_time.setText(new StringBuilder()
                    .append(String.format("%02d",hourOfDay))
                    .append(":")
                    .append(String.format("%02d",minute)));
        },HOUR, MINUTE, true).show();
    }

    //提交按钮
    public void save(View view) {
        if (cao3_dunkuangbianhao.getText().toString().equals("")) {
            Toast.makeText(this, "请填写3#槽内吨框编号", Toast.LENGTH_SHORT).show();
            return;
        }
        if (cao4_dunkuangbianhao.getText().toString().equals("")) {
            Toast.makeText(this, "请填写4#槽内吨框编号", Toast.LENGTH_SHORT).show();
            return;
        }
        if (neibuwendu.getText().toString().equals("")) {
            Toast.makeText(this, "请填写堆肥车间内部温度", Toast.LENGTH_SHORT).show();
            return;
        }
        if (waibuwendu.getText().toString().equals("")) {
            Toast.makeText(this, "请填写堆肥车间外部温度", Toast.LENGTH_SHORT).show();
            return;
        }
        new AlertDialog.Builder(this)
                .setTitle("确定保存吗？")
                .setCancelable(false)
                .setNegativeButton("取消", ((dialog, which) ->
                        Toast.makeText(this, "取消保存", Toast.LENGTH_SHORT).show()))
                .setPositiveButton("确定", (dialog, which) -> {
                    //提交请求
                    RequestQueue queue = Volley.newRequestQueue(this);
                    String url = Config.url + "/sjq/sjqCompostProcessFermentation/add";
                    StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                            new Response.Listener<String>() {
                                @Override
                                public void onResponse(String response) {
                                    Log.d("jy", response);
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        String code = jsonObject.getString("code");

                                        if (code.startsWith("2"))
                                            Toast.makeText(DuifeiFajiaowendu.this,
                                                    "保存成功", Toast.LENGTH_SHORT).show();
                                        else
                                            Toast.makeText(DuifeiFajiaowendu.this,
                                                    "保存失败！", Toast.LENGTH_SHORT).show();
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Toast.makeText(DuifeiFajiaowendu.this,
                                    "保存失败" + error.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }) {
                        @Override
                        protected Map<String, String> getParams() throws AuthFailureError {
                            Map<String, String> map=new HashMap<>();
                            map.put("date",jilu_date.getText().toString());
                            map.put("time",jilu_time.getText().toString());
                            map.put("third_num",cao3_dunkuangbianhao.getText().toString());
                            map.put("third_one",cao3_diyitian.getText().toString());
                            map.put("third_two",cao3_diertian.getText().toString());
                            map.put("third_three",cao3_disantian.getText().toString());
                            map.put("third_four",cao3_disitian.getText().toString());
                            map.put("third_five",cao3_diwutian.getText().toString());
                            map.put("third_six",cao3_diliutian.getText().toString());
                            map.put("third_seven",cao3_diqitian.getText().toString());
                            map.put("third_eight",cao3_dibatian.getText().toString());
                            map.put("fourth_num",cao4_dunkuangbianhao.getText().toString());
                            map.put("fourth_one",cao4_diyitian.getText().toString());
                            map.put("fourth_two",cao4_diertian.getText().toString());
                            map.put("fourth_three",cao4_disantian.getText().toString());
                            map.put("fourth_four",cao4_disitian.getText().toString());
                            map.put("fourth_five",cao4_diwutian.getText().toString());
                            map.put("fourth_six",cao4_diliutian.getText().toString());
                            map.put("fourth_seven",cao4_diqitian.getText().toString());
                            map.put("fourth_eight",cao4_dibatian.getText().toString());

                            map.put("internal_temperature", neibuwendu.getText().toString());
                            map.put("external_temperature", waibuwendu.getText().toString());

                            map.put("remarks", remark.getText().toString());
                            map.put("factory", factory);
                            return map;
                        }
                    };
                    stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                            DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                    queue.add(stringRequest);
                })
                .show();
    }

    public void show3(View view) {
        if (expand_3.isExpanded()){
            textView3.setText("+ 3#槽内吨框温度(℃)");
        }else{
            textView3.setText("- 3#槽内吨框温度(℃)");
            expand_4.collapse();
        }
        expand_3.toggle();
    }
    public void show4(View view) {
        if (expand_4.isExpanded()){
            textView4.setText("+ 4#槽内吨框温度(℃)");
        }else{
            textView4.setText("- 4#槽内吨框温度(℃)");
            expand_3.collapse();
        }
        expand_4.toggle();
    }
}